#!/usr/bin/python3
#coding = utf-8

import ctypes,sys
import socket
import urllib.request
import re
import time
import string
from colorama import init
from termcolor import colored

#在windows下使用Colorama显示颜色
init()

#同时请求多只股票
url = 'https://qt.gtimg.cn/q='

with open("stockCode.txt", "r") as f:
    for line in f.readlines():
        line = line.strip('\n')  #去掉列表中每一个元素的换行符
        
        if len(line) > 0:
            url += (line + ',')

if url.endswith(','):
    url = url[0:len(url)-1]

headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17'

while True:
    request = urllib.request.Request(url, headers=headers)
    resp = urllib.request.urlopen(request)
    data = resp.read().decode('gb2312')

    if data.find(';') == -1:
        dataList = [data]
    else:
        dataList = data.split(';')

    # print(dataList)

    for item in dataList:
        if len(item) < 3:
            continue
        else:
            stocklist = item.split('~')
            
            # print(stocklist[31])

            # stocklist[0] = stocklist[0][stocklist[0].find('=')+2:]

            # curr = float(stocklist[3])            # current
            # yend = float(stocklist[2])            # yesterday end
            # percent = (curr / yend - 1) * 100 # percent
            # diff = curr - yend                # Price difference
        
            # disp = '{:5s} | {:>8s} | {:>6.2f}% | {:>6.2f}'.format(stocklist[1],stocklist[3], stocklist[32], stocklist[31])
            disp = '{:5s} | {:>8s} | {:>6s}% | {:>6s}'.format(stocklist[1],stocklist[3], stocklist[32], stocklist[31])
        
            if float(stocklist[31]) == 0.0:
                print(colored(disp, 'white'))
            elif float(stocklist[31]) > 0.0:
                print(colored(disp, 'red'))
            else: # percent < 0.0
                print(colored(disp, 'green'))

    print('\r')
    #10s 更新一次
    time.sleep(100)